<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>async和await结合AJAX</title>
</head>
<body>
<h1>Promise封装AJAX</h1>
<hr>
<button>使用回调函数发送AJAX</button>
<script>
    //接口地址 https://api.apiopen.top/getJoke

    //获取元素对象
    const btn = document.querySelector('button')

    //获取Ajax请求的promise对象
    function sendAJAX(url) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest()
            xhr.open('GET', url)
            xhr.send()
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(xhr.response)
                    } else {
                        reject(xhr.status)
                    }
                }
            }
        })
    }


    btn.addEventListener("click", async function () {
        //获取段子的信息
        try {
            const duanzi = await sendAJAX('https://api.apiopen.top/getJoke')
            console.log(duanzi)
        } catch (e) {
            console.log(e)
        }

    })
</script>
</body>
</html>